package com.cz.fra.android;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.cz.fra.android.entity.User;
import com.cz.fra.android.logic.AuthLogic;
import com.cz.fra.android.logic.UserLogic;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity implements OnClickListener{
	private Button commit;
	private TextView register;
	private EditText name;
	private EditText password;
	public static final int GET_DATA = 1;
	private ArrayList<User> userList = new ArrayList<User>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.login);
        initView();
        FishReportApplication.getInstance().addActivities(this);
    }

    private void initView() {
    	commit = (Button) findViewById(R.id.commit);
    	register = (TextView) findViewById(R.id.register);
    	name = (EditText) findViewById(R.id.name);
    	password = (EditText) findViewById(R.id.password);
    	register.setOnClickListener(this);
    	commit.setOnClickListener(this);
    }
    
	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
		    case R.id.commit:
		    	new Thread(runnable).start();
			    break;
		    case R.id.register:
			    intent.setClass(LoginActivity.this, RegisterActivity.class);
			    startActivity(intent);
			    break;
	        default:
				break;
		}
	}
	
	Runnable runnable = new Runnable(){

		@Override
		public void run() {
			HttpPost httpRequest = new HttpPost(Config.URL_LOGIN);
			List<NameValuePair>	nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("username", name.getText()+""));
			nameValuePairs.add(new BasicNameValuePair("password", password.getText()+""));
			try {
				httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
				HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); 
				if(httpResponse.getStatusLine().getStatusCode() == 200) {
//					System.out.println("Login : " + EntityUtils.toString(httpResponse.getEntity()) );
					if(EntityUtils.toString(httpResponse.getEntity()).equalsIgnoreCase("success")){
						putDatabase(name.getText()+"", password.getText()+"");
						//saveUserName(name.getText()+"");
						Intent intent = new Intent();
						intent.putExtra("username", name.getText()+"");
						intent.setClass(LoginActivity.this, MainActivity.class);
						startActivity(intent);
					}else{
						
					}
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
			Message msg = new Message();
			msg.what = GET_DATA;
			mHandler.sendMessage(msg);
		}

	};
	
	private Handler mHandler = new Handler() {
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
    		    case GET_DATA:
    		    	
    		    	break;
    		}
    	}
    };
    
    private void saveUserName(String name) {
    	User user = new User();
		user.setUsername(name);
		userList.add(user);
    	UserLogic.getInstance(this).insertUsers(userList);	
    }
    
    private void putDatabase(String username, String password) {
    	AuthLogic.getInstance(this).insertAuthInfo(username, password, "fasle");
    	
    }
    
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {  
            exitDialog();  
            return true;  
        }  
        return true;  
    }

	private void exitDialog() {
		AlertDialog.Builder builder = new Builder(this);  
        builder.setMessage("Confirm exit?");  
        builder.setTitle("Alert");  
        builder.setPositiveButton("YES",  
        new android.content.DialogInterface.OnClickListener() {  
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                dialog.dismiss();  
                FishReportApplication.getInstance().exit();
            }  
        });  
        builder.setNegativeButton("NO",  
        new android.content.DialogInterface.OnClickListener() {  
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                dialog.dismiss();  
            }  
        });  
        builder.create().show();  
	}
}
